// winBiblix.cs
//
//  Copyright (C) 2007 BOUTRY Arnaud arnaud@lordphoenix.info
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 
//
//

using System;
using System.Collections;
using Gtk;
using Mono.Unix;

namespace biblix
{
	public enum biblixaction
	{
		bxnone,
		bxadd,
		bxedit,
		bxdelete,
		bxnotedit
	}
	public partial class winBiblix : Gtk.Window
	{
		private booklist mybase;
		private biblixaction currentaction = biblixaction.bxnone;
		private book workbook,oldbook;
		public winBiblix() : base(Gtk.WindowType.Toplevel)
		{
			this.Build();
			Mono.Unix.Catalog.Init("i8n1","./locale");
			string filepath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
			filepath +="/.biblix/booklist.blix";
			mybase = new booklist(filepath);
			
			ListStore modBooklist = new ListStore(typeof(book));
			trvBooklist.AppendColumn(Catalog.GetString("Livres"),new CellRendererText(),new Gtk.TreeCellDataFunc(RenderTitle));
			trvBooklist.Model = modBooklist;
			trvBooklist.Selection.Changed += new EventHandler(SelectedBookChange);
			
			//initialisation de la liste des genres
			foreach(string genre in mybase.GetGenreList())
				cbxListGenre.AppendText(genre);
			
			//Initialisation de la liste des sources
			foreach (string source in mybase.GetSourcesList())
				cbxSource.AppendText(source);
			
			txtComment.Buffer.Changed += OnEditBook;
			txtSynopsis.Buffer.Changed += OnEditBook;
			ShowBookList();
		}
		
		private void RenderTitle(Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter)
		{
			book curbook =(book)model.GetValue(iter,0);
			(cell as Gtk.CellRendererText).Text=curbook.titre;
		}
		
		private void ShowBookList()
		{
			(trvBooklist.Model as ListStore).Clear();
			IEnumerator i = mybase.getidlist().GetEnumerator();
			while(i.MoveNext())
			{
				book curbook = mybase.getbook(i.Current.ToString());
				if (curbook!=null)
					(trvBooklist.Model as ListStore).AppendValues(curbook);
			}
		}
		
		private void ShowBookDetails(book currentbook)
		{
			currentaction = biblix.biblixaction.bxnotedit;
			entAuthor.Text="";
			entTitle.Text="";
			entSerieTitle.Text="";
			entPublishYear.Text="";
			cbxListGenre.Active=-1;
			spbNote.Value=-1;
			spbVolume.Value=0;
			ckbReadBook.Active=false;
			ckbPret.Active=false;
			cbxSource.Active=-1;
			txtComment.Buffer.Clear();
			txtSynopsis.Buffer.Clear();
			if (currentbook != null)
			{
				entAuthor.Text = currentbook.auteur;
				entTitle.Text = currentbook.titre;
				entSerieTitle.Text = currentbook.serie;
				spbNote.Value = currentbook.note;
				spbVolume.Value = currentbook.volume;
				ckbReadBook.Active = currentbook.lu;
				ckbPret.Active = currentbook.pret;
				txtComment.Buffer.Text = currentbook.commentaire;
				txtSynopsis.Buffer.Text = currentbook.resume;
				entPublishYear.Text = currentbook.publishyear;
				
				if (currentbook.shortdate!="01/01/0001")					
					lblDate.LabelProp = currentbook.longdate;
				else 
					lblDate.LabelProp = Catalog.GetString("date...");

				int index = -1;
				if (!String.IsNullOrEmpty(currentbook.genre))
				{
					string searchgenre ="";
					ListStore listegenremodel = (ListStore)cbxListGenre.Model;
					System.Collections.IEnumerator i = listegenremodel.GetEnumerator();
					while ((i.MoveNext())&(searchgenre !=currentbook.genre))
					{
						object[] row = (System.Object[])i.Current;
						searchgenre = row[0].ToString();
						index +=1;
					}
				}
				cbxListGenre.Active = index;
				
				int indexsource = -1;
				if(!String.IsNullOrEmpty(currentbook.source))
					{
					ListStore listesourcemodel = (ListStore)cbxSource.Model;
					IEnumerator j = listesourcemodel.GetEnumerator();
					string searchsource ="";
					while ((j.MoveNext())&(searchsource != currentbook.source))
					{
						object[] row =(System.Object[])j.Current;
						searchsource = row[0].ToString();
						indexsource+=1;
					}
					}
				cbxSource.Active = indexsource;
			}
			currentaction = biblix.biblixaction.bxnone;
		}
		
		private void savebook()
		{
			switch (currentaction)
			{
				case biblix.biblixaction.bxadd:
					mybase.addbook(workbook);
					break;
				case biblix.biblixaction.bxedit :
					mybase.updatebook(workbook);
					break;
			}
			btnSaveBook.Sensitive = false;
			btnUndo.Sensitive = false;
			currentaction = biblixaction.bxnone;
		}
		protected virtual void SelectedBookChange(object sender, EventArgs args)
		{
			switch (currentaction)
			{
				case biblixaction.bxedit:
					MessageDialog dlg = new MessageDialog(this,Gtk.DialogFlags.DestroyWithParent,
					                                      Gtk.MessageType.Question,Gtk.ButtonsType.YesNo,
					                                      String.Format(Catalog.GetString("Des modifications ont été apportées au livre ,{0} voulez vous les enregistrer?"),
					                                      workbook.titre));
					ResponseType result = (ResponseType)dlg.Run();
					if (result==ResponseType.Yes)
					{
						mybase.updatebook(workbook);
						btnSaveBook.Sensitive = false;
						btnUndo.Sensitive = false;
						currentaction = biblixaction.bxnone;
					}
					else 
					{
						workbook = oldbook;
						ShowBookDetails(workbook);
						btnUndo.Sensitive = true;
						currentaction = biblixaction.bxnone;
					}
					dlg.Hide();
					dlg.Destroy();
					break;
				case biblixaction.bxadd :
					break;
				
				case biblixaction.bxnone:
					TreeIter selectediter;
					if (trvBooklist.Selection.GetSelected(out selectediter))
					{
						book selectedbook = (book)((trvBooklist.Model as ListStore).GetValue(selectediter,0));
						workbook = selectedbook;
						ShowBookDetails(selectedbook);
					}
					else ShowBookDetails(null);
					break;
			}
		}

		protected virtual void OnDeleteEvent (object o, Gtk.DeleteEventArgs args)
		{
			Application.Quit ();
			args.RetVal = true;
		}

		protected virtual void OnbtnListeClicked (object sender, System.EventArgs e)
		{
			ShowBookList();
		}

		protected virtual void OnBtnAddbookClicked (object sender, System.EventArgs e)
		{
			if (currentaction == biblixaction.bxnone)
			{
				dlgAddBook dlg = new dlgAddBook(mybase);
				ResponseType result = (ResponseType)dlg.Run();
				if (result==ResponseType.Ok)
				{
					book newbook = dlg.newbook;
					mybase.addbook(newbook);
					this.ShowBookList();
				}
				dlg.Hide();
				dlg.Destroy();
				
			}
			else 
			{
				MessageDialog dlg = new MessageDialog(this,DialogFlags.DestroyWithParent,MessageType.Question,
				                                      ButtonsType.YesNo,Catalog.GetString("Des modification sont en cours voulez vous les enregistrer?"));
				if (dlg.Run()==(int)ResponseType.Yes)
				{
					savebook();
				}
				dlg.Hide();
				dlg.Destroy();
			}
		}

		protected virtual void OnCkbFilterClicked (object sender, System.EventArgs e)
		{
			cbxFilterItem.Sensitive=ckbFilter.Active;
			cbxFilterValue.Sensitive=ckbFilter.Active;
			if (!ckbFilter.Active)
			{
				cbxFilterItem.Active=-1;
				cbxFilterValue.Active=-1;
			}
		}

		protected virtual void OnEditBook (object sender, System.EventArgs e)
		{
			if(workbook != null)
			{
				if (currentaction != biblix.biblixaction.bxnotedit)
				{
					if (currentaction != biblixaction.bxadd)
						currentaction = biblix.biblixaction.bxedit;
					if (oldbook==null)
						oldbook = (book)workbook.Clone();// Ne sauvegarder que si cela n'a pas déjà été fait.
					workbook.titre = entTitle.Text;
					workbook.auteur = entAuthor.Text;
					workbook.genre = cbxListGenre.ActiveText;
					workbook.serie = entSerieTitle.Text;
					workbook.volume = spbVolume.ValueAsInt;
					workbook.note = spbNote.ValueAsInt;
					workbook.lu = ckbReadBook.Active;
					workbook.source = cbxSource.ActiveText;
					workbook.pret = ckbPret.Active;
					workbook.resume = txtSynopsis.Buffer.Text;
					workbook.commentaire = txtComment.Buffer.Text;
					workbook.publishyear = entPublishYear.Text;
					btnSaveBook.Sensitive = true;
					btnUndo.Sensitive = true;
				}
			}
		}

		protected virtual void OnBtnSaveBookClicked (object sender, System.EventArgs e)
		{
			savebook();
			oldbook=null;
		}

		protected virtual void OnBtnDateClicked (object sender, System.EventArgs e)
		{
			if (workbook == null)
				return;
			if (oldbook==null)
						oldbook = (book)workbook.Clone();
			dlgDateSelect dlgdate;
			if (workbook.shortdate!="01/01/0001")
				 dlgdate = new dlgDateSelect(workbook.date);
			else
				dlgdate = new dlgDateSelect();
			dlgdate.Run();
			workbook.date = dlgdate.SelectedDate;
			if (workbook.shortdate!="01/01/0001")					
					lblDate.LabelProp = workbook.longdate;
				else 
					lblDate.LabelProp = Catalog.GetString("date...");			
			dlgdate.Hide();
			dlgdate.Destroy();
			currentaction= biblixaction.bxedit;
			btnSaveBook.Sensitive = true;
			btnUndo.Sensitive = true;
		}

		protected virtual void OnBtnUndoClicked (object sender, System.EventArgs e)
		{
			switch (currentaction)
			{
				case biblixaction.bxedit:
					workbook = oldbook;
					ShowBookDetails(workbook);
					btnUndo.Sensitive = true;
					currentaction = biblixaction.bxnone;
					break;
				case biblixaction.bxadd:
					TreeIter iter;
					trvBooklist.Selection.GetSelected(out iter);
					(trvBooklist.Model as ListStore).Remove(ref iter);
					ShowBookDetails(null);
					workbook = null;
					break;
			}
			oldbook = null;
			btnSaveBook.Sensitive = false;
			btnUndo.Sensitive = false;
			currentaction = biblixaction.bxnone;
		}

		protected virtual void OnBtnAutreGenreClicked (object sender, System.EventArgs e)
		{
			biblix.dlgNewRefValue dlg = new dlgNewRefValue("Ajout d'un genre littéraire");
			ResponseType result = (ResponseType)dlg.Run();
			if (result==Gtk.ResponseType.Ok)
				cbxListGenre.AppendText(dlg.refvalue);
			dlg.Hide();
			dlg.Destroy();
		}

		protected virtual void OnBtnAddSourceClicked (object sender, System.EventArgs e)
		{
			biblix.dlgNewRefValue dlg = new dlgNewRefValue(Catalog.GetString("Ajout d'une source supplémentaire"));
			ResponseType result = (ResponseType)dlg.Run();
			if (result == ResponseType.Ok)
				cbxSource.AppendText(dlg.refvalue);
			dlg.Hide();
			dlg.Destroy();
		}

		protected virtual void OnBtnDeleteBookClicked (object sender, System.EventArgs e)
		{
			if (currentaction != biblixaction.bxnone)
			{
				MessageDialog dlg = new MessageDialog(this,DialogFlags.DestroyWithParent,MessageType.Warning,
				                                      ButtonsType.Close,"Attention des modifications sont en cours Enregistrez les ou annulez les avant de faire autre chose");
				dlg.Run();
				dlg.Hide();
				dlg.Destroy();
			}
			else
			{
				MessageDialog dlg = new MessageDialog(this,DialogFlags.DestroyWithParent,MessageType.Question,
				                                      ButtonsType.OkCancel,"Voulez vous vraiment supprimer le livre \"{0}\" de votre bibliothèque ?",workbook.titre);
				if ((ResponseType)dlg.Run()==ResponseType.Ok)
				{
					bool result = mybase.deletebook(workbook.id);
					if (result)
						workbook = null;
					ShowBookList();
					ShowBookDetails(workbook);
				}
				dlg.Hide();
				dlg.Destroy();
			}
		}
	}
}
